//
//  SPIssueViewController.m
//  Sport
//
//  Created by Cass on 2017/11/23.
//  Copyright © 2017年 Cass. All rights reserved.
//

#define MarginTop 12
#define MarginLeft 17
#define PictureViewWH ((SCREEN_WIDTH - 2 * MarginTop -3 * MarginLeft ) / 4)

#import "SPIssueViewController.h"
#import <CoreLocation/CoreLocation.h>
#import "SPCollectionViewCell.h"
#import "SPAddCollectionViewCell.h"
#import "SPLimitsViewController.h"
#import <QMUIKit.h>
@interface SPIssueViewController ()<UITextViewDelegate,CLLocationManagerDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,CTAssetsPickerControllerDelegate,UICollectionViewDelegate,UICollectionViewDataSource>
@property (weak, nonatomic) IBOutlet UIView *notesPictureView;

@property (weak, nonatomic) IBOutlet UITextView *textView;
@property (weak, nonatomic) UILabel *label;
@property (weak, nonatomic) IBOutlet UILabel *locLabel;
@property (weak, nonatomic) IBOutlet UIButton *openBtn;
@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic, strong) CLGeocoder *geocoder;
@property (nonatomic, copy) NSString *locationCity;
@property (nonatomic, strong) UIImagePickerController *imagePickerVC;
@property (nonatomic, strong) NSMutableArray *photosArray;
@property (nonatomic, strong) UICollectionView *collectionView;

@end

@implementation SPIssueViewController
- (UICollectionView *)collectionView{
    if (!_collectionView) {
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
        flowLayout.itemSize = CGSizeMake(PictureViewWH, PictureViewWH);
        flowLayout.sectionInset = UIEdgeInsetsMake(MarginTop, MarginTop, 0, MarginTop);
        self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.textView.frame), SCREEN_WIDTH, 300) collectionViewLayout:flowLayout];
        _collectionView.backgroundColor = [UIColor whiteColor];
        self.collectionView.delegate = self;
        self.collectionView.dataSource = self;
    }
    return _collectionView;
}
- (UIImagePickerController *)imagePickerVC{
    if (!_imagePickerVC) {
        _imagePickerVC = [[UIImagePickerController alloc]init];
        _imagePickerVC.delegate = self;
    }
    return _imagePickerVC;
}
- (CLGeocoder *)geocoder{
    if (!_geocoder) {
        _geocoder = [[CLGeocoder alloc]init];
    }
    return _geocoder;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.collectionView registerClass:[SPCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    [self.collectionView registerClass:[SPAddCollectionViewCell class] forCellWithReuseIdentifier:@"identifier"];
    [self.notesPictureView addSubview:self.collectionView];
    [self setupBasic];
}

- (void)setupBasic{
    self.photosArray = [NSMutableArray array];
    self.textView.returnKeyType = UIReturnKeyDone;
    self.textView.delegate = self;
    self.navigationItem.title = @"发布动态";
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 5, 150, 21)];
    label.textColor = [UIColor grayColor];
    label.text = @"这一刻...";
    self.label = label;
    [self.textView addSubview:_label];
    self.locationManager = [[CLLocationManager alloc]init];
    self.locationManager.delegate = self;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
        [self.locationManager requestWhenInUseAuthorization];
    }
    //开始定位不断调用起代理方法
    [self.locationManager startUpdatingLocation];
    
    UIBarButtonItem *rightItem = [UIBarButtonItem itemWithImage:@"" selectedImage:@"" title:@"发布" target:self action:@selector(onRightItemTapped)];
    self.navigationItem.rightBarButtonItem = rightItem;
    UIBarButtonItem *leftItem = [UIBarButtonItem itemWithImage:@"" selectedImage:@"" title:@"取消" target:self action:@selector(onLeftItemTapped)];
    self.navigationItem.leftBarButtonItem = leftItem;
    
}
- (void)alertAction{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *photoAction = [UIAlertAction actionWithTitle:@"选择相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"调用相册");
        [self onAddBtnTapped:nil];
    }];
    UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"调用相机");
        [self takePhoto];
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"取消");
    }];
    [alertVC addAction:photoAction];
    [alertVC addAction:cameraAction];
    [alertVC addAction:cancelAction];
    [self presentViewController:alertVC animated:YES completion:nil];
}
- (void)onAddBtnTapped:(UIButton *)sender{
    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
        if (status != PHAuthorizationStatusAuthorized) return ;
        CTAssetsPickerController *picker = [[CTAssetsPickerController alloc]init];
        picker.delegate = self;
        // 显示选择的索引
        picker.showsSelectionIndex = YES;
        // 设置相册的类型：相机胶卷 + 自定义相册
        picker.assetCollectionSubtypes = @[@(PHAssetCollectionSubtypeSmartAlbumUserLibrary),@(PHAssetCollectionSubtypeAlbumRegular)];
        // 不需要显示空的相册
        picker.showsEmptyAlbums = NO;
        //添加到主队列
        dispatch_async(dispatch_get_main_queue(), ^{
            [self presentViewController:picker animated:YES completion:nil];
        });
//        [self presentViewController:picker animated:YES completion:nil];
    }];
}

//拍照
-(void)takePhoto{
   
    UIImagePickerController * imagePickerVC = [[UIImagePickerController alloc] init];
    // 设置资源来源
    imagePickerVC.sourceType = UIImagePickerControllerSourceTypeCamera;
    // 设置可用的媒体类型、默认只包含kUTTypeImage，如果想选择视频，请添加kUTTypeMovie
    imagePickerVC.mediaTypes = @[(NSString *)kUTTypeMovie, (NSString *)kUTTypeImage];
    // 设置代理，遵守UINavigationControllerDelegate, UIImagePickerControllerDelegate 协议
    imagePickerVC.delegate = self;
    // 是否允许编辑
    imagePickerVC.allowsEditing = YES;
    // 如果选择的是视屏，允许的视屏时长为20秒
    imagePickerVC.videoMaximumDuration = 20;
    // 允许的视屏质量（如果质量选取的质量过高，会自动降低质量）
    imagePickerVC.videoQuality = UIImagePickerControllerQualityTypeHigh;
    // 相机获取媒体的类型（照相、录制视屏）
    imagePickerVC.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
    // 使用前置还是后置摄像头
    imagePickerVC.cameraDevice = UIImagePickerControllerCameraDeviceRear;
    // 是否看起闪光灯
    imagePickerVC.cameraFlashMode = UIImagePickerControllerCameraFlashModeAuto;
    imagePickerVC.showsCameraControls = YES;
    // model出控制器
    [self presentViewController:imagePickerVC animated:YES completion:nil];


    
}


//icon_zuji_1
- (void)onRightItemTapped{
    

    if (self.textView.text.length > 0) {

        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"application/json", @"text/json", @"text/javascript", @"text/plain", nil];
        manager.requestSerializer = [AFHTTPRequestSerializer serializer];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        //    manager.requestSerializer.timeoutInterval = 20;
         NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
        NSString *url = [NSString stringWithFormat:@"http://39.108.132.194/Sport/issue.php"];
        NSDictionary *dict = @{
                               @"id":[userDefault objectForKey:@"ID"],
                               @"address":self.locLabel.text,
                               @"message":self.textView.text
                               };
        [manager POST:url parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
            for (int i = 0; i < _photosArray.count; i++) {
                UIImage *image = _photosArray[i];
                NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
                //在网络开发中，上传文件时，文件不允许被覆盖，文件重名
                //所以在上传时，可以用系统时间为文件名
                NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
                //设置时间格式
                [formatter setDateFormat:@"yyyyMMddHHmmssSSS"];
                NSString *dateString = [formatter stringFromDate:[NSDate date]];
                NSString *fileName = [NSString stringWithFormat:@"%@.jpg",dateString];
                [formData appendPartWithFileData:imageData name:@"file[]" fileName:fileName mimeType:@"image/jpeg"];
            }
        } progress:^(NSProgress * _Nonnull uploadProgress) {
                    dispatch_async(dispatch_get_main_queue(), ^{
//                        NSLog(@"--上传进度--%@",uploadProgress);
                        UIView *parentView = self.navigationController.view;
                        [QMUITips showLoading:[NSString stringWithFormat:@"发送中%@",uploadProgress.localizedDescription] inView:parentView];
//
                    });
            NSLog(@"--上传进度--%@",uploadProgress);
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSLog(@"--上传成功--%@",responseObject);
            NSData *strData = responseObject;
            NSString *strInfo = [[NSString alloc]initWithData:strData encoding:NSUTF8StringEncoding];
            NSLog(@"%@",strInfo);
            
            [SPHUDUtil showHUDWithDismissTimeInterval:1 message:@"发送成功" hudType:SPHUDTypeSuccess];
            [self dismissViewControllerAnimated:YES completion:nil];
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"--上传失败--%@",error);
            NSData *data = error.userInfo[@"com.alamofire.serialization.response.error.data"];
            NSString *str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"服务器错误原因--%@",str);
            
            [SPHUDUtil showHUDWithDismissTimeInterval:1 message:@"发送失败" hudType:SPHUDTypeError];
        }];

    }else{
        [SPHUDUtil showHUDWithDismissTimeInterval:1 message:@"发送内容为空" hudType:SPHUDTypeError];
    }
     [self.navigationController popViewControllerAnimated:YES];
}


- (void)onLeftItemTapped{
    [self.textView resignFirstResponder];
    [self dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark - UITextViewDelegate -
- (void)textViewDidChange:(UITextView *)textView{
    if (textView.text.length > 0) {
        self.label.hidden = YES;
    }else{
        self.label.hidden = NO;
    }
}

-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if ([text isEqualToString:@"\n"]) {
        [self.textView resignFirstResponder];
        return NO;
    }
    return YES;
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
//    [self.textView resignFirstResponder];
    [self.view endEditing:YES];
}

#pragma mark - UIImagePickerControllerDelegate -

// 选择图片成功调用此方法

//相机拍照
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    [picker dismissViewControllerAnimated:YES completion:nil];
    NSLog(@"%@",info);
    UIImage *image = nil;
    image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
    [self.photosArray addObject:image];
    [self.collectionView reloadData];
}



- (void)assetsPickerController:(CTAssetsPickerController *)picker didFinishPickingAssets:(NSArray *)assets{
    [picker dismissViewControllerAnimated:YES completion:nil];
    NSLog(@"%@",assets);
    
    for (NSInteger i = 0; i < assets.count; i++) {
        PHAsset *asset = assets[i];
        PHImageRequestOptions *options = [[PHImageRequestOptions alloc]init];
        options.resizeMode = PHImageRequestOptionsResizeModeExact;
        options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
        
        [[PHImageManager defaultManager] requestImageDataForAsset:asset options:options resultHandler:^(NSData * _Nullable imageData, NSString * _Nullable dataUTI, UIImageOrientation orientation, NSDictionary * _Nullable info) {
            UIImage *image = [UIImage imageWithData:imageData];
            [self.photosArray addObject:image];
            [self.collectionView reloadData];
            NSLog(@"照片张数:%lu",(unsigned long)self.photosArray.count);
        }];
    }
}

- (void)deleteImg:(UIButton *)sender{
    NSInteger index = sender.tag - 100;
    [self.photosArray removeObjectAtIndex:index];
    [self.collectionView reloadData];
}
- (BOOL)assetsPickerController:(CTAssetsPickerController *)picker shouldSelectAsset:(PHAsset *)asset{
    if ((self.photosArray.count + picker.selectedAssets.count) >= 9) {
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"最多只能选择九张" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleDefault handler:nil];
        [alertVC addAction:action];
        [picker presentViewController:alertVC animated:YES completion:nil];
        return NO;
    }
    return YES;
}
#pragma mark - CLLocationManagerDelegate -
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
    CLLocation *location = locations.lastObject;
    
    [self.geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        if (error == nil) {
            CLPlacemark *placemark = placemarks.firstObject;
//            self.locationCity = [placemark.administrativeArea stringByAppendingString:[NSString stringWithFormat:@"•%@",placemark.locality]];
            self.locationCity = placemark.locality;
            self.locationCity = [self.locationCity stringByAppendingString:[NSString stringWithFormat:@"·%@",placemark.name]];
            NSLog(@"%@",self.locationCity);
            self.locLabel.text = self.locationCity;
        }else{
            NSLog(@"失败:%@",error);
        }
    }];
    [manager stopUpdatingLocation];
}

#pragma mark - collectionView代理 -
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    NSInteger number = 0;
    if (self.photosArray.count >= 9) {
        number = 9;
    }else{
        number = self.photosArray.count + 1;
    }
    return number;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    SPAddCollectionViewCell *addCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"identifier" forIndexPath:indexPath];
    if (self.photosArray.count == 0) {
        return addCell;
    }else{
        SPCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
        if (indexPath.item + 1 > self.photosArray.count) {
            return addCell;
        }else{
            cell.imageV.image = self.photosArray[indexPath.item];
            [cell.imageV addSubview:cell.deleteBtn];
            cell.deleteBtn.tag = indexPath.item + 100;
            [cell.deleteBtn addTarget:self action:@selector(deleteImg:) forControlEvents:UIControlEventTouchUpInside];
        }
        
        return cell;
    }
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.item + 1 > self.photosArray.count) {
        [self alertAction];
    }
}
- (IBAction)permissionButton:(UIButton *)sender {
    SPLimitsViewController *limitVC = [[UIStoryboard storyboardWithName:@"Issue" bundle:[NSBundle mainBundle]] instantiateViewControllerWithIdentifier:NSStringFromClass([SPLimitsViewController class])];
    limitVC.block = ^(NSString *string) {
        [self.openBtn setTitle:string forState:UIControlStateNormal];
    };
    [self.navigationController pushViewController:limitVC animated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


@end
